﻿//另存为txt文件，默认utf8
//https://developer.mozilla.org/zh-CN/docs/Web/API/Window/showSaveFilePicker
//https://developer.mozilla.org/zh-CN/docs/Web/API/FileSystemFileHandle
export async function SaveAsTxtFile(filename, contents) {

    try {

        //显示文件选择器，返回FileSystemFileHandle
        const fileHandle = await window.showSaveFilePicker({
            suggestedName: filename,
            types: [
                {
                    description: "txt文件",
                    accept: {
                        "text/plain": [".txt"]
                    }
                }]
        });

        //创建一个 FileSystemWritableFileStream 用来写入
        const writable = await fileHandle.createWritable();

        //将文件内容写入到流中
        await writable.write(contents);

        //关闭文件并将内容写入磁盘
        await writable.close();

    } catch (error) {
        console.error(error);
    }
}

//打开txt文件，默认utf8
//https://developer.mozilla.org/zh-CN/docs/Web/API/Window/showOpenFilePicker
//https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
export async function OpenTxtFile() {

    try {

        //显示文件选择器，返回FileSystemFileHandle对象的 Array 数组
        const fileHandles = await window.showOpenFilePicker({
            types: [
                {
                    description: "txt文件",
                    accept: {
                        "text/plain": [".txt"],
                    },
                },
            ],

            //只能选择一个文件
            multiple: false,
        });

        if (!fileHandles || !fileHandles.length)
            return "没有选择文件";

        //获取第一个文件
        const fileHandle = fileHandles[0];

        //获取File对象
        const file = await fileHandle.getFile();

        if (!file)
            return "无法获取文件对象";

        //读取文本文件，按照utf-8
        const contents = await file.text();

        return contents;

    } catch (error) {
        console.error(error);
        return error.toString();
    }
}

//获取选择目录下的txt文件
//https://developer.mozilla.org/zh-CN/docs/Web/API/Window/showDirectoryPicker
//https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryHandle
export async function GetTxtFileFromSelectDirectory() {

    try {
        //显示一个目录选择器并在用户选择后返回一个 FileSystemDirectoryHandle 对象。
        const dirHandle = await window.showDirectoryPicker();

        var txtFileHandles = new Array();
        var txtFileInfos = new Array();

        for await (const [filename, fileHandle] of dirHandle) {

            //文件的kind=file，目录的kind=directory
            if (fileHandle.kind === "file") {
                const file = await fileHandle.getFile();
                if ((file !== null) && (file.type === "text/plain")) {

                    //缓存txt文件对象
                    txtFileHandles.push(fileHandle);

                    txtFileInfos.push({ filename: file.name, size: file.size });
                }
            }
        }

        //缓存txt文件对象数组
        window.TxtFileHandles = txtFileHandles;

        console.log(window.TxtFileHandles);

    } catch (error) {
        console.error(error);
    }

    return txtFileInfos;
}

//从选择的目录中加载txt文件
export async function LoadTxtFileFromSelectDirectory(txtFilename) {

    try {

        //从选择的目录下边缓存txt文件对象数组中查找txt文件
        const fileHandle = window.TxtFileHandles.find(x => x.name == txtFilename);

        if (fileHandle == null)
            return "文件不存在";

        const file = await fileHandle.getFile();

        if (!file)
            return "无法获取文件对象";

        //读取文本文件，按照utf-8
        const contents = await file.text();

        return contents;

    } catch (error) {
        console.error(error);
        return error.toString();
    }
}